#import "AddItemViewController.h"

@interface AddItemViewController () <UITextFieldDelegate, UITextViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UITextField *titleField;
@property (nonatomic, strong) UITextView *descTextView;
@property (nonatomic, strong) UILabel *placeholderLabel;

// 新增：时间显示相关
@property (nonatomic, strong) UIButton *timeDisplayButton;
@property (nonatomic, strong) UIDatePicker *timePicker;
@property (nonatomic, strong) UIView *timePickerContainer;
@property (nonatomic, assign) BOOL isTimePickerVisible;

// 新增：底部时间选择器相关
@property (nonatomic, strong) UIView *timePickerOverlay;
@property (nonatomic, strong) UIView *timePickerBottomView;
@property (nonatomic, strong) UIDatePicker *bottomTimePicker;

@property (nonatomic, strong) UISegmentedControl *typeSegment;
@property (nonatomic, strong) UISegmentedControl *prioritySegment;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIButton *timeButton;


@end

@implementation AddItemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 根据编辑模式设置标题
    self.title = self.isEditMode ? @"编辑事项" : @"添加事项";
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    
    // 设置导航栏 - 使用 back 图片
    UIImage *backImage = [UIImage imageNamed:@"back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    [self setupUI];
    [self setupConstraints];
    
    // 键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 在视图完全加载后填充编辑数据
    if (self.isEditMode && self.editingItem) {
        [self populateFieldsWithItem:self.editingItem];
    }
}

// 添加 setupUI 方法
- (void)setupUI {
    // 创建滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    
    // 创建内容视图
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
    
    // 创建事项标题section
    UIView *titleSection = [self createSectionWithTitle:@"事项标题"];
    
    self.titleField = [[UITextField alloc] init];
    self.titleField.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleField.placeholder = @"请输入事项标题";
    self.titleField.font = [UIFont systemFontOfSize:16];
    self.titleField.borderStyle = UITextBorderStyleRoundedRect;
    self.titleField.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    self.titleField.layer.borderWidth = 0;
    self.titleField.delegate = self;
    [titleSection addSubview:self.titleField];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.titleField.leadingAnchor constraintEqualToAnchor:titleSection.leadingAnchor constant:20],
        [self.titleField.trailingAnchor constraintEqualToAnchor:titleSection.trailingAnchor constant:-20],
        [self.titleField.topAnchor constraintEqualToAnchor:titleSection.topAnchor constant:50],
        [self.titleField.heightAnchor constraintEqualToConstant:48]
    ]];
    
    // 创建详细描述section
    UIView *descSection = [self createSectionWithTitle:@"详细描述"];
    
    self.descTextView = [[UITextView alloc] init];
    self.descTextView.translatesAutoresizingMaskIntoConstraints = NO;
    self.descTextView.font = [UIFont systemFontOfSize:16];
    self.descTextView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    self.descTextView.layer.cornerRadius = 8;
    self.descTextView.delegate = self;
    [descSection addSubview:self.descTextView];
    
    // 添加占位符标签
    self.placeholderLabel = [[UILabel alloc] init];
    self.placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.placeholderLabel.text = @"请输入详细描述（可选）";
    self.placeholderLabel.font = [UIFont systemFontOfSize:16];
    self.placeholderLabel.textColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0];
    [self.descTextView addSubview:self.placeholderLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.descTextView.leadingAnchor constraintEqualToAnchor:descSection.leadingAnchor constant:20],
        [self.descTextView.trailingAnchor constraintEqualToAnchor:descSection.trailingAnchor constant:-20],
        [self.descTextView.topAnchor constraintEqualToAnchor:descSection.topAnchor constant:50],
        [self.descTextView.heightAnchor constraintEqualToConstant:80],
        
        [self.placeholderLabel.leadingAnchor constraintEqualToAnchor:self.descTextView.leadingAnchor constant:5],
        [self.placeholderLabel.topAnchor constraintEqualToAnchor:self.descTextView.topAnchor constant:8]
    ]];
    
    // 创建提醒时间section
    UIView *timeSection = [self createSectionWithTitle:@"提醒时间"];
    
    self.timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.timeButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.timeButton.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    self.timeButton.layer.cornerRadius = 8;
    self.timeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.timeButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.timeButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
    [self.timeButton setTitleColor:[UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0] forState:UIControlStateNormal];
    [self.timeButton addTarget:self action:@selector(showTimePickerFromBottom) forControlEvents:UIControlEventTouchUpInside];
    [timeSection addSubview:self.timeButton];
    
    // 设置默认时间显示
    [self updateTimeDisplay];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.timeButton.leadingAnchor constraintEqualToAnchor:timeSection.leadingAnchor constant:20],
        [self.timeButton.trailingAnchor constraintEqualToAnchor:timeSection.trailingAnchor constant:-20],
        [self.timeButton.topAnchor constraintEqualToAnchor:timeSection.topAnchor constant:50],
        [self.timeButton.heightAnchor constraintEqualToConstant:48]
    ]];
    
    // 创建事项类型section
    UIView *typeSection = [self createSectionWithTitle:@"事项类型"];
    
    self.typeSegment = [[UISegmentedControl alloc] initWithItems:@[@"一次性", @"每日重复"]];
    self.typeSegment.translatesAutoresizingMaskIntoConstraints = NO;
    self.typeSegment.selectedSegmentIndex = 0;
    self.typeSegment.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    self.typeSegment.selectedSegmentTintColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    [self.typeSegment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected];
    [typeSection addSubview:self.typeSegment];
    
    UILabel *typeHintLabel = [[UILabel alloc] init];
    typeHintLabel.translatesAutoresizingMaskIntoConstraints = NO;
    typeHintLabel.text = @"每日重复事项将在每天的指定时间提醒";
    typeHintLabel.font = [UIFont systemFontOfSize:12];
    typeHintLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    [typeSection addSubview:typeHintLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.typeSegment.leadingAnchor constraintEqualToAnchor:typeSection.leadingAnchor constant:20],
        [self.typeSegment.trailingAnchor constraintEqualToAnchor:typeSection.trailingAnchor constant:-20],
        [self.typeSegment.topAnchor constraintEqualToAnchor:typeSection.topAnchor constant:50],
        [self.typeSegment.heightAnchor constraintEqualToConstant:40],
        
        [typeHintLabel.leadingAnchor constraintEqualToAnchor:typeSection.leadingAnchor constant:20],
        [typeHintLabel.topAnchor constraintEqualToAnchor:self.typeSegment.bottomAnchor constant:12]
    ]];
    
    // 创建重要程度section
    UIView *prioritySection = [self createSectionWithTitle:@"重要程度"];
    
    self.prioritySegment = [[UISegmentedControl alloc] initWithItems:@[@"普通", @"重要", @"紧急"]];
    self.prioritySegment.translatesAutoresizingMaskIntoConstraints = NO;
    self.prioritySegment.selectedSegmentIndex = 0;
    self.prioritySegment.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    [self.prioritySegment addTarget:self action:@selector(priorityChanged:) forControlEvents:UIControlEventValueChanged];
    [prioritySection addSubview:self.prioritySegment];
    
    // 设置初始颜色
    [self priorityChanged:self.prioritySegment];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.prioritySegment.leadingAnchor constraintEqualToAnchor:prioritySection.leadingAnchor constant:20],
        [self.prioritySegment.trailingAnchor constraintEqualToAnchor:prioritySection.trailingAnchor constant:-20],
        [self.prioritySegment.topAnchor constraintEqualToAnchor:prioritySection.topAnchor constant:50],
        [self.prioritySegment.heightAnchor constraintEqualToConstant:40]
    ]];
    
    // 创建保存按钮
    [self createSaveButton];
}

- (void)populateFieldsWithItem:(NSDictionary *)item {
    // 确保所有UI元素都已创建
    if (!self.titleField || !self.descTextView || !self.prioritySegment || !self.typeSegment) {
        return;
    }
    
    // 填充标题
    if (item[@"title"]) {
        self.titleField.text = item[@"title"];
    }
    
    // 填充描述
    if (item[@"desc"]) {
        self.descTextView.text = item[@"desc"];
        self.placeholderLabel.hidden = self.descTextView.text.length > 0;
    }
    
    // 填充时间
    NSString *timeString = item[@"time"];
    if (timeString && timeString.length > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"HH:mm";
        NSDate *time = [formatter dateFromString:timeString];
        if (time) {
            if (!self.timePicker) {
                self.timePicker = [[UIDatePicker alloc] init];
                self.timePicker.datePickerMode = UIDatePickerModeTime;
            }
            self.timePicker.date = time;
            [self updateTimeDisplay];
        }
    }
    
    // 填充优先级
    NSString *priority = item[@"priority"];
    if (priority) {
        if ([priority isEqualToString:@"normal"]) {
            self.prioritySegment.selectedSegmentIndex = 0;
        } else if ([priority isEqualToString:@"medium"]) {
            self.prioritySegment.selectedSegmentIndex = 1;
        } else if ([priority isEqualToString:@"high"]) {
            self.prioritySegment.selectedSegmentIndex = 2;
        }
        // 安全调用 priorityChanged
        if (self.prioritySegment) {
            [self priorityChanged:self.prioritySegment];
        }
    }
    
    // 填充类型
    if (item[@"isDaily"]) {
        BOOL isDaily = [item[@"isDaily"] boolValue];
        self.typeSegment.selectedSegmentIndex = isDaily ? 1 : 0;
    }
}

- (void)saveAction {
    if (self.titleField.text.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入事项标题" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    // 显示保存中的提示
    self.saveButton.enabled = NO;
    NSString *buttonTitle = self.isEditMode ? @"更新中..." : @"保存中...";
    [self.saveButton setTitle:buttonTitle forState:UIControlStateNormal];
    
    // 格式化时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    
    NSDate *timeToSave;
    if (self.timePicker) {
        timeToSave = self.timePicker.date;
    } else {
        timeToSave = [NSDate date];
    }
    NSString *timeString = [formatter stringFromDate:timeToSave];
    
    // 获取优先级 - 添加安全检查
    NSArray *priorities = @[@"normal", @"medium", @"high"];
    NSString *priority = @"normal"; // 默认值
    if (self.prioritySegment && self.prioritySegment.selectedSegmentIndex >= 0 && self.prioritySegment.selectedSegmentIndex < priorities.count) {
        priority = priorities[self.prioritySegment.selectedSegmentIndex];
    }
    
    // 获取类型 - 添加安全检查
    BOOL isDaily = NO; // 默认值
    if (self.typeSegment) {
        isDaily = (self.typeSegment.selectedSegmentIndex == 1);
    }
    
    // 安全获取文本内容
    NSString *titleText = self.titleField.text ?: @"";
    NSString *descText = self.descTextView.text ?: @"";
    
    // 创建事项字典 - 确保所有值都不为 nil
    NSMutableDictionary *itemData = [@{
        @"title": titleText,
        @"desc": descText,
        @"time": timeString ?: @"00:00",
        @"priority": priority,
        @"isDaily": @(isDaily),
        @"done": @NO
    } mutableCopy];
    
    // 如果是编辑模式，保留原有的完成状态
    if (self.isEditMode && self.editingItem && self.editingItem[@"done"]) {
        itemData[@"done"] = self.editingItem[@"done"];
    }
    
    // 通知代理
    if (self.delegate) {
        if (self.isEditMode && [self.delegate respondsToSelector:@selector(didEditItem:atIndex:)]) {
            [self.delegate didEditItem:[itemData copy] atIndex:self.editingIndex];
        } else if (!self.isEditMode && [self.delegate respondsToSelector:@selector(didAddNewItem:)]) {
            [self.delegate didAddNewItem:[itemData copy]];
        }
    }
    
    // 显示成功提示并返回
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 恢复按钮状态
        self.saveButton.enabled = YES;
        NSString *originalTitle = self.isEditMode ? @"更新事项" : @"保存事项";
        [self.saveButton setTitle:originalTitle forState:UIControlStateNormal];
        
        // 返回上一个页面
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void)createSaveButton {
    self.saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.saveButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSString *buttonTitle = self.isEditMode ? @"更新事项" : @"保存事项";
    [self.saveButton setTitle:buttonTitle forState:UIControlStateNormal];
    
    // 设置按钮样式
    self.saveButton.backgroundColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    self.saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.saveButton.layer.cornerRadius = 25;
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.saveButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.saveButton];
    
    // 设置保存按钮的约束
    [NSLayoutConstraint activateConstraints:@[
        [self.saveButton.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:40],
        [self.saveButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-40],
        [self.saveButton.heightAnchor constraintEqualToConstant:50],
        [self.saveButton.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-30]
    ]];
}

- (void)setupConstraints {
    // 滚动视图约束
    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor]
    ]];
    
    // 获取所有section视图
    NSMutableArray *sections = [NSMutableArray array];
    for (UIView *subview in self.contentView.subviews) {
        if ([subview isKindOfClass:[UIView class]] && subview.backgroundColor == [UIColor whiteColor] && subview != self.saveButton) {
            [sections addObject:subview];
        }
    }
    
    // 设置section之间的约束
    UIView *lastSection = nil;
    for (int i = 0; i < sections.count; i++) {
        UIView *section = sections[i];
        
        [NSLayoutConstraint activateConstraints:@[
            [section.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
            [section.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20]
        ]];
        
        if (i == 0) {
            // 第一个section
            [section.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20].active = YES;
        } else {
            // 其他section
            [section.topAnchor constraintEqualToAnchor:lastSection.bottomAnchor constant:20].active = YES;
        }
        
        // 设置section高度
        if (i == 0) { // 事项标题section
            [section.heightAnchor constraintEqualToConstant:118].active = YES;
        } else if (i == 1) { // 详细描述section
            [section.heightAnchor constraintEqualToConstant:150].active = YES;
        } else if (i == 2) { // 提醒时间section
            [section.heightAnchor constraintEqualToConstant:118].active = YES;
        } else if (i == 3) { // 事项类型section
            [section.heightAnchor constraintEqualToConstant:122].active = YES;
        } else if (i == 4) { // 重要程度section
            [section.heightAnchor constraintEqualToConstant:110].active = YES;
        }
        
        lastSection = section;
    }
    
    // 保存按钮约束 - 连接到最后一个section
    if (lastSection) {
        [self.saveButton.topAnchor constraintEqualToAnchor:lastSection.bottomAnchor constant:30].active = YES;
    }
}

- (UIView *)createSectionWithTitle:(NSString *)title {
    UIView *section = [[UIView alloc] init];
    section.translatesAutoresizingMaskIntoConstraints = NO;
    section.backgroundColor = [UIColor whiteColor];
    section.layer.cornerRadius = 16;
    section.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.08].CGColor;
    section.layer.shadowOpacity = 1;
    section.layer.shadowOffset = CGSizeMake(0, 2);
    section.layer.shadowRadius = 8;
    [self.contentView addSubview:section];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    titleLabel.textColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    [section addSubview:titleLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [titleLabel.leadingAnchor constraintEqualToAnchor:section.leadingAnchor constant:20],
        [titleLabel.topAnchor constraintEqualToAnchor:section.topAnchor constant:20]
    ]];
    
    return section;
}

//- (void)setupConstraints {
//    UIView *lastSection = nil;
//    NSArray *sections = @[];
//    
//    // 找到所有section视图
//    for (UIView *subview in self.contentView.subviews) {
//        if (subview.backgroundColor == [UIColor whiteColor] && subview != self.saveButton) {
//            sections = [sections arrayByAddingObject:subview];
//        }
//    }
//    
//    // 设置section之间的约束
//    for (int i = 0; i < sections.count; i++) {
//        UIView *section = sections[i];
//        
//        [NSLayoutConstraint activateConstraints:@[
//            [section.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
//            [section.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20]
//        ]];
//        
//        if (i == 0) {
//            // 第一个section - 事项标题
//            [section.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20].active = YES;
//            [section.heightAnchor constraintEqualToConstant:118].active = YES; // 20 + 50 + 48 = 118
//        } else {
//            // 其他section
//            [section.topAnchor constraintEqualToAnchor:lastSection.bottomAnchor constant:20].active = YES;
//            
//            if (i == 1) { // 详细描述section
//                [section.heightAnchor constraintEqualToConstant:170].active = YES; // 20 + 50 + 80 + 20 = 170
//            } else if (i == 2) { // 提醒时间section
//                [section.heightAnchor constraintEqualToConstant:118].active = YES; // 20 + 50 + 48 = 118
//            } else if (i == 3) { // 事项类型section
//                [section.heightAnchor constraintEqualToConstant:140].active = YES; // 20 + 50 + 40 + 12 + 18 + 20 = 160
//            } else if (i == 4) { // 重要程度section
//                [section.heightAnchor constraintEqualToConstant:110].active = YES; // 20 + 50 + 40 = 110
//            }
//        }
//        
//        lastSection = section;
//    }
//    
//    // 保存按钮约束
//    [self.saveButton.topAnchor constraintEqualToAnchor:lastSection.bottomAnchor constant:30].active = YES;
//    
//    // 滚动视图约束
//    [NSLayoutConstraint activateConstraints:@[
//        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
//        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
//        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
//        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
//        
//        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
//        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
//        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
//        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
//        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor]
//    ]];
//}

#pragma mark - Actions

- (void)showTimePickerFromBottom {
    // 创建遮罩层
    self.timePickerOverlay = [[UIView alloc] init];
    self.timePickerOverlay.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    self.timePickerOverlay.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.timePickerOverlay];
    
    // 添加点击手势关闭选择器
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTimePickerFromBottom)];
    [self.timePickerOverlay addGestureRecognizer:tapGesture];
    
    // 创建底部容器
    self.timePickerBottomView = [[UIView alloc] init];
    self.timePickerBottomView.backgroundColor = [UIColor whiteColor];
    self.timePickerBottomView.translatesAutoresizingMaskIntoConstraints = NO;
    self.timePickerBottomView.layer.cornerRadius = 16;
    self.timePickerBottomView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    [self.view addSubview:self.timePickerBottomView];
    
    // 创建顶部工具栏
    UIView *toolbar = [[UIView alloc] init];
    toolbar.translatesAutoresizingMaskIntoConstraints = NO;
    toolbar.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.0];
    [self.timePickerBottomView addSubview:toolbar];
    
    // 取消按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelButton setTitleColor:[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(hideTimePickerFromBottom) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:cancelButton];
    
    // 完成按钮
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
    doneButton.translatesAutoresizingMaskIntoConstraints = NO;
    [doneButton setTitle:@"完成" forState:UIControlStateNormal];
    doneButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    [doneButton setTitleColor:[UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(confirmTimeSelection) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:doneButton];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = @"选择提醒时间";
    titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    titleLabel.textColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [toolbar addSubview:titleLabel];
    
    // 创建时间选择器
    self.bottomTimePicker = [[UIDatePicker alloc] init];
    self.bottomTimePicker.translatesAutoresizingMaskIntoConstraints = NO;
    self.bottomTimePicker.datePickerMode = UIDatePickerModeTime;
    self.bottomTimePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
    
    // 如果之前有选择过时间，设置为当前时间
    if (self.timePicker) {
        self.bottomTimePicker.date = self.timePicker.date;
    } else {
        // 设置默认时间为当前时间
        self.bottomTimePicker.date = [NSDate date];
    }
    
    [self.timePickerBottomView addSubview:self.bottomTimePicker];
    
    // 设置约束
    [NSLayoutConstraint activateConstraints:@[
        // 遮罩层约束
        [self.timePickerOverlay.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [self.timePickerOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.timePickerOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.timePickerOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        // 底部容器约束
        [self.timePickerBottomView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.timePickerBottomView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.timePickerBottomView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [self.timePickerBottomView.heightAnchor constraintEqualToConstant:300],
        
        // 工具栏约束
        [toolbar.topAnchor constraintEqualToAnchor:self.timePickerBottomView.topAnchor],
        [toolbar.leadingAnchor constraintEqualToAnchor:self.timePickerBottomView.leadingAnchor],
        [toolbar.trailingAnchor constraintEqualToAnchor:self.timePickerBottomView.trailingAnchor],
        [toolbar.heightAnchor constraintEqualToConstant:50],
        
        // 工具栏按钮约束
        [cancelButton.leadingAnchor constraintEqualToAnchor:toolbar.leadingAnchor constant:20],
        [cancelButton.centerYAnchor constraintEqualToAnchor:toolbar.centerYAnchor],
        
        [doneButton.trailingAnchor constraintEqualToAnchor:toolbar.trailingAnchor constant:-20],
        [doneButton.centerYAnchor constraintEqualToAnchor:toolbar.centerYAnchor],
        
        [titleLabel.centerXAnchor constraintEqualToAnchor:toolbar.centerXAnchor],
        [titleLabel.centerYAnchor constraintEqualToAnchor:toolbar.centerYAnchor],
        
        // 时间选择器约束
        [self.bottomTimePicker.topAnchor constraintEqualToAnchor:toolbar.bottomAnchor constant:20],
        [self.bottomTimePicker.leadingAnchor constraintEqualToAnchor:self.timePickerBottomView.leadingAnchor],
        [self.bottomTimePicker.trailingAnchor constraintEqualToAnchor:self.timePickerBottomView.trailingAnchor],
        [self.bottomTimePicker.bottomAnchor constraintEqualToAnchor:self.timePickerBottomView.bottomAnchor constant:-20]
    ]];
    
    // 初始位置设置在屏幕下方
    self.timePickerBottomView.transform = CGAffineTransformMakeTranslation(0, 300);
    self.timePickerOverlay.alpha = 0;
    
    // 动画显示
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.timePickerBottomView.transform = CGAffineTransformIdentity;
        self.timePickerOverlay.alpha = 1;
    } completion:nil];
}

- (void)hideTimePickerFromBottom {
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.timePickerBottomView.transform = CGAffineTransformMakeTranslation(0, 300);
        self.timePickerOverlay.alpha = 0;
    } completion:^(BOOL finished) {
        [self.timePickerOverlay removeFromSuperview];
        [self.timePickerBottomView removeFromSuperview];
        self.timePickerOverlay = nil;
        self.timePickerBottomView = nil;
        self.bottomTimePicker = nil;
    }];
}

- (void)confirmTimeSelection {
    // 更新时间选择器的值
    if (!self.timePicker) {
        self.timePicker = [[UIDatePicker alloc] init];
        self.timePicker.datePickerMode = UIDatePickerModeTime;
    }
    self.timePicker.date = self.bottomTimePicker.date;
    
    // 更新显示
    [self updateTimeDisplay];
    
    // 隐藏选择器
    [self hideTimePickerFromBottom];
}

- (void)updateTimeDisplay {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    
    NSDate *timeToFormat;
    if (self.timePicker) {
        timeToFormat = self.timePicker.date;
    } else {
        timeToFormat = [NSDate date];
    }
    
    NSString *timeString = [formatter stringFromDate:timeToFormat];
    [self.timeDisplayButton setTitle:[NSString stringWithFormat:@"提醒时间: %@", timeString] forState:UIControlStateNormal];
}

- (void)priorityChanged:(UISegmentedControl *)sender {
    UIColor *selectedColor;
    switch (sender.selectedSegmentIndex) {
        case 0: // 普通
            selectedColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
            break;
        case 1: // 重要
            selectedColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
            break;
        case 2: // 紧急
            selectedColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0];
            break;
        default:
            selectedColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
            break;
    }
    
    sender.selectedSegmentTintColor = selectedColor;
    [sender setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected];
}

- (void)cancelAction {
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - Keyboard Handling

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 获取键盘高度
    CGFloat keyboardHeight = keyboardFrame.size.height;
    
    // 调整滚动视图的内容边距
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
    
    // 动画调整
    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
    
    // 如果当前有输入框处于编辑状态，滚动到可见区域
    UIView *activeField = nil;
    if ([self.titleField isFirstResponder]) {
        activeField = self.titleField;
    } else if ([self.descTextView isFirstResponder]) {
        activeField = self.descTextView;
    }
    
    if (activeField) {
        CGRect fieldFrame = [activeField convertRect:activeField.bounds toView:self.scrollView];
        [self.scrollView scrollRectToVisible:fieldFrame animated:YES];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 恢复滚动视图的内容边距
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.scrollView.contentInset = contentInsets;
        self.scrollView.scrollIndicatorInsets = contentInsets;
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    self.placeholderLabel.hidden = textView.text.length > 0;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    self.placeholderLabel.hidden = YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.placeholderLabel.hidden = textView.text.length > 0;
}

@end
